proc int2bits_without_leading_0 {i} {
     #returns a bitslist, e.g. int2bits 10 => {1 0 1 0}
     set res ""
     while {$i>0} {
         set res [expr {$i%2}]$res
         set i [expr {$i/2}]
     }
     if {$res==""} {set res 0}
#     split $res ""
     set res
 }
proc int2bits {x} {
   string map {
   0 {0 0 0} 1 {0 0 1} 2 {0 1 0} 3 {0 1 1} 4 {1 0 0} 5 {1 0 1} 6 {1 1 0} 7 {1 1 1}
   } [split [format %o $x] ""]
 } ;#RS - note however that the bit sequence is multiples of 3 long:
proc int2bits_sf {x} {
   string map {
   0 {FFF} 1 {FFP} 2 {FPF} 3 {FPP} 4 {PFF} 5 {PFP} 6 {PPF} 7 {PPP}
   } [split [format %o $x] ""]
 } ;#RS - note however that the bit sequence is multiples of 3 long:

 proc bits2int {bits} {
     #returns integer equivalent of a bitlist
     set res 0
     foreach i $bits {
         set res [expr {$res*2+$i}]
     }
     set res
 }

proc setbitvalue {variable index value} {
	if {$value} {
		expr {$variable | (1<<$index)}
	} else {
		expr {$variable & ~(1<<$index)}
	}
}

proc getbitvalue {variable index } {
	set c [expr {$variable & (1<<$index)}]
	if {$c==[expr {1<<$index}]} {
		return 1
	} else {
		return 0
	}
}

proc handle_string_special {old_string} {
	return [string map {  \\ \\\\\\\\ \' \\\\' \" \\" } $old_string] 
	#return [string map {\" \\" \' \\' \( \\\( \) \\\) \\\\ \\\\\\\\} $old_string] 
}

proc trimend {txt trim} {
	if {[string match "*$trim" $txt]} {
		if {[set n [string last $trim $txt]] >= 0} {
			set txt [string range $txt 0 [expr {$n-1}]]
		}
	}
	return $txt
}

proc trimfirst {txt trim} {
	if {[string match "$trim*" $txt]} {
		if {[set n [string first $trim $txt]] >= 0} {
			set txt [string range $txt [expr {$n+[string length $trim]}] end]
		}
	}
	return $txt
} 
